﻿/*
 * 功用：字符串hash签名
 * 创建时间：2021-6-10 17:30:39
 * 作者：王浩力
 */
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;

namespace WebNetCorePhoneErp.Model.Tool
{
    /// <summary>
    /// 字符串Hash签名
    /// </summary>
    public static class HashEncrypt
    {
        /// <summary>
        ///SHA256 位字符串Hash签名
        /// </summary>
        /// <param name="strIN"></param>
        /// <returns></returns>
        public static string SHA256Encrypt(string strIN)
        {
            byte[] tmpByte;
            SHA256 sha256 = new SHA256Managed();
            tmpByte = sha256.ComputeHash(GetKeyByteArray(strIN));
            sha256.Clear();
            return GetStringValue(tmpByte);
        }

        /// <summary>
        /// SHA512 位字符串Hash签名
        /// </summary>
        /// <param name="strIN"></param>
        /// <returns></returns>
        public static string SHA512Encrypt(string strIN)
        {
            byte[] tmpByte;
            SHA512 sha512 = new SHA512Managed();
            tmpByte = sha512.ComputeHash(GetKeyByteArray(strIN));
            sha512.Clear();
            return GetStringValue(tmpByte);
        }


        public static byte[] GetKeyByteArray(string strKey)
        {
            ASCIIEncoding Asc = new ASCIIEncoding();
            int tmpStrLen = strKey.Length;
            byte[] tmpByte = new byte[tmpStrLen - 1];
            tmpByte = Asc.GetBytes(strKey);
            return tmpByte;
        }

        /// <summary>
        /// 将byte字节数组转换为大写的16进制字符串
        /// </summary>
        /// <param name="bytes">byte字节数组</param>
        /// <returns></returns>
        public static string GetStringValue(byte[] bytes)
        {
            StringBuilder builder = new StringBuilder();
            for (int i = 0; i < bytes.Length; i++)
            {
                builder.Append(bytes[i].ToString("X2"));
            }
            return builder.ToString();
        }

    }
}
